<template>
  <div>
    <!-- 大客户订单提报 -->
    <TopFilter :list="topFilterList" ref="top" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="wkcOrderSubmissionsCdlr"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onSyncTableData="tableChange"
        :isSelectColumn="false"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <!-- <template slot="controls" slot-scope="props"> -->
        <template slot="controls">
          <multiuse-button size="small" type="primary" :disabled="isDisabled" @click="addHandle(1)">新 增</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(2)">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <Drawer :visible.sync="addVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <addModel :isClientOrder="isClientOrder" @close="addcloseHandler" />
    </Drawer>
    <Drawer :visible.sync="emmitVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <emitModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
    <Drawer :visible.sync="detailVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <detailModel :rowData="formData" @close="detailcloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="isClient" :title="'订购方式'" destroyOnClose :width="'30%'" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <div>
        <multiuse-button :containerStyle="{ marginLeft: '15%', marginRight: '12%', marginTop: '28px' }" size="big" type="primary" @click="addDiffHandle(1)">客户订购</multiuse-button>
        <multiuse-button size="big" type="primary" @click="addDiffHandle(2)">非客户订购</multiuse-button>
      </div>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right',
        }"
      >
        <el-button @click="addDiffHandle(3)">关 闭</el-button>
      </div>
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getDeadlineTime, getStatus } from '@/api/dealerSale/salesPlan/MonthPlanReport';
import { getListZB, exportList, getNotPage, deleteOrderById, subOrderById, getDealerUser } from '@/api/dealerSale/OrderManagement/OrderSubmissionC';
import addModel from './addModel';
import emitModel from './emitModel';
import detailModel from './detailModel';
import { exportExcelFile } from '@/utils';
import moment from 'moment';
export default {
  name: 'zjTemplateDistribution',
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchParams: {
        // searchType: 1,
        // saveType: 'DLR',
        // majorType: 1,
        isDealer: 10041001,
      },
      fetchApi: getListZB,
      formData: {},
      exportLoading: false,
      emmitVisible: false,
      issearch: false,
      detailVisible: false,
      addVisible: false,
      isClient: false,
      isClientOrder: true,
      isDisabled: false,
      showData: {
        currMonth: moment().format('YYYY年MM月'),
        checkStatus: false,
        beginDate: '',
        endDate: '',
      },
    };
  },
  mixins: [dictionary],
  components: {
    addModel,
    emitModel,
    detailModel,
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.init();
    this.getUser();
  },
  methods: {
    //初始化数据
    async init() {
      const res = await getStatus();
      const res1 = await getDeadlineTime({ reportDate: moment().format('YYYY-MM'), setType: 24201002 });
      if (res.resultCode === 200) {
        this.showData.checkStatus = res.data;
      }
      if (res1.resultCode === 200) {
        if (res1.data !== null) {
          this.showData.beginDate = res1.data.beginDate;
          this.showData.endDate = res1.data.endDate;
        } else {
          this.showData.beginDate = null;
          this.showData.endDate = null;
        }
      }
      this.isDisabled = !res.data;
    },
    addDiffHandle(type) {
      if (type === 1) {
        this.isClient = false;
        this.addVisible = true;
        this.isClientOrder = true;
      } else if (type === 2) {
        this.isClient = false;
        this.addVisible = true;
        this.isClientOrder = false;
      } else {
        this.isClient = false;
      }
    },
    tableChange(val) {
      val.map((x) => {
        x.buildRebateTotalAmountLocalShow = x.buildRebateTotalAmountStart + x.buildRebateTotalAmount;
      });
    },

    selectChangeHandle(row) {},
    async getNotPage(orderType) {
      let list = await getNotPage({ orderType: orderType });
      this.topFilterList.map((x) => {
        if (x.fieldName == 'orderDetailType') {
          x.itemList = list.data.map((x) => ({ text: x.subName, value: x.subId }));
        }
      });
    },
    seacherFun() {
      this.issearch = true;
    },
    async addHandle(type) {
      if (type == 1) {
        if (this.showData.endDate == null || this.showData.beginDate == null) {
          this.$notify.warning({ title: '提示信息', message: '联系管理员配置增补订单提报时间！' });
          return;
        } else if (this.showData.endDate > moment().format('YYYY-MM-DD') && this.showData.beginDate < moment().format('YYYY-MM-DD')) {
          this.isClient = true;
        } else {
          this.$notify.warning({ title: '提示信息', message: '当前时间不允许增补订单提报！' });
          return;
        }
      } else {
        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$refs.top.SUBMIT_FORM();
            this.exportLoading = true;
            exportList(this.fetchParams)
              .then((response) => {
                exportExcelFile(response.data, 'C端增补订单提报');
                this.exportLoading = false;
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      }
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async editHandle(data, type) {
      this.formData = data;
      if (type == 1) {
        this.emmitVisible = true;
      } else if (type == 2) {
        this.detailVisible = true;
      } else if (type == 3) {
        await this.$confirm('是否进行提报?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await subOrderById({ orderId: data.orderId });
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
              });
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
      } else {
        await this.$confirm('是否确定取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await deleteOrderById({ orderId: data.orderId });
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '取消成功',
                type: 'success',
              });
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
      }
    },
    emitcloseHandler(val) {
      this.emmitVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    addcloseHandler(val) {
      this.addVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    detailcloseHandler() {
      this.detailVisible = false;
    },
    async getUser() {
      let res = await getDealerUser();
      let empList = res.data.map((x) => ({ text: x.employeeName, value: x.userId + '' }));
      this.columns.find((item) => item.dataIndex === 'createdBy').editItems = empList; //操作姓名
      this.columns.find((item) => item.dataIndex === 'createdBy').filterItems = empList;
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2408'),
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          dateType: 'month',
          clearable: true,
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 200,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)} disabled={props.row.orderStatus != 24081001}>
                  编辑
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
                  详情
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 4)} disabled={props.row.orderStatus != 24081001}>
                  取消
                </multiuse-button>
              </div>
            );
          },
        },

        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2410'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2410')}</span>;
          },
        },
        {
          title: '紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2408'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderStatus, '2408')}</span>;
          },
        },

        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2409'),
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '收车地址',
          dataIndex: 'address',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '送达城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系电话',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '提报数量',
          dataIndex: 'orderTotalNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        // {
        //   title: '订单总金额',
        //   dataIndex: 'orderTotalAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   precision: 2,
        // },
        // {
        //   title: '折扣总金额',
        //   dataIndex: 'discountTotalAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '返利使用总金额',
        //   dataIndex: 'rebateTotalAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        // },
        // {
        //   title: '单车返利总金额',
        //   dataIndex: 'singleRebateTotalAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '建店返利总金额',
        //   dataIndex: 'buildRebateTotalAmountLocalShow',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '实付总金额',
        //   dataIndex: 'realPayTotalAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        // },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editType: 'select',
          editItems: [],
        },
        {
          title: '创建日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
      ];
    },
  },
};
</script>
